package com.paishen.common.album;

import android.app.Activity;
import android.content.ContentResolver;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Canvas;
import android.graphics.Rect;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.provider.MediaStore;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.TextView;

import com.bumptech.glide.Glide;

import java.io.File;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import com.paishen.common.R;
import com.paishen.common.util.BaseUtil;
import com.paishen.common.widget.TitleLayout;


public class PhotoAlbumActivity extends Activity {

    private static final int RESULT_CODE_WALL = 3422;

    public static class PhotoAlbum {
        private String pathName;
        private int fileCount;
        private String firstImagePath;

        public PhotoAlbum(String pathName, int fileCount, String firstImagePath) {
            this.pathName = pathName;
            this.fileCount = fileCount;
            this.firstImagePath = firstImagePath;
        }
    }

    private RecyclerView viewRecycler;
    private AlbumAdapter adapter;

    @Override
    protected void onDestroy() {
        super.onDestroy();
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        getWindow().setBackgroundDrawableResource(android.R.color.transparent);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            // 透明状态栏
            getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
        }
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_photo_album);

        TitleLayout layTitle = (TitleLayout) findViewById(R.id.lay_title);
        ImageView viewBack = (ImageView) LayoutInflater.from(this).inflate(R.layout.layout_title_menu_image, null);
        viewBack.setImageResource(R.mipmap.common_back);
        viewBack.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                onBackPressed();
            }
        });
        layTitle.pushContent(viewBack, getString(R.string.album) , null, false);

        viewRecycler = (RecyclerView) findViewById(R.id.view_recycler);
        viewRecycler.setLayoutManager(new LinearLayoutManager(this));
        viewRecycler.setAdapter(adapter = new AlbumAdapter());
        viewRecycler.setItemAnimator(new DefaultItemAnimator());
        viewRecycler.addItemDecoration(new RecyclerView.ItemDecoration() {
            @Override
            public void getItemOffsets(Rect outRect, View view, RecyclerView parent, RecyclerView.State state) {
                outRect.bottom = 1;
            }

            @Override
            public void onDraw(Canvas c, RecyclerView parent, RecyclerView.State state) {
                super.onDraw(c, parent, state);
                c.drawColor(0xFFDDDDDD);
            }
        });

        adapter.set(getImagePathsByContentProvider());
    }

    /**
     * 使用ContentProvider读取SD卡所有图片。
     */
    private ArrayList<PhotoAlbum> getImagePathsByContentProvider() {
        Uri mImageUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;

        String key_MIME_TYPE = MediaStore.Images.Media.MIME_TYPE;
        String key_DATA = MediaStore.Images.Media.DATA;

        ContentResolver mContentResolver = getContentResolver();

        // 只查询jpg和png的图片
        Cursor cursor = mContentResolver.query(mImageUri, new String[]{key_DATA},
                key_MIME_TYPE + "=? or " + key_MIME_TYPE + "=? or " + key_MIME_TYPE + "=?",
                new String[]{"image/jpg", "image/jpeg", "image/png"},
                MediaStore.Images.Media.DATE_MODIFIED);

        ArrayList<PhotoAlbum> list = null;
        if (cursor != null) {
            if (cursor.moveToLast()) {
                //路径缓存，防止多次扫描同一目录
                HashSet<String> cachePath = new HashSet<>();
                list = new ArrayList<>();
                while (true) {
                    // 获取图片的路径
                    String imagePath = cursor.getString(0);
                    File parentFile = new File(imagePath).getParentFile();
                    String parentPath = parentFile.getAbsolutePath();
                    //不扫描重复路径
                    if (!cachePath.contains(parentPath)) {
                        list.add(new PhotoAlbum(parentPath, getImageCount(parentFile),
                                getFirstImagePath(parentFile)));
                        cachePath.add(parentPath);
                    }
                    if (!cursor.moveToPrevious()) {
                        break;
                    }
                }
            }
            cursor.close();
        }
        return list;
    }

    /**
     * 获取目录中图片的个数。
     */
    private int getImageCount(File folder) {
        int count = 0;
        File[] files = folder.listFiles();
        if (files != null) {
            for (File file : files) {
                if (Util.isImage(file.getName())) {
                    count++;
                }
            }
        }
        return count;
    }

    /**
     * 获取目录中最新的一张图片的绝对路径。
     */
    private String getFirstImagePath(File folder) {
        File[] files = folder.listFiles();
        for (int i = files.length - 1; i >= 0; i--) {
            File file = files[i];
            if (Util.isImage(file.getName())) {
                return file.getAbsolutePath();
            }
        }
        return null;
    }


    private static final class AlbumAdapter extends RecyclerView.Adapter<AlbumAdapter.ViewHolder> {
        final List<PhotoAlbum> photoAlbumList = new ArrayList<>();

        public void set(List<PhotoAlbum> dataList) {
            photoAlbumList.clear();
            photoAlbumList.addAll(dataList);
            notifyItemRangeChanged(0, getItemCount());
        }

        public class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
            public ViewHolder(View view) {
                super(view);
                view.setOnClickListener(this);
            }

            private PhotoAlbum itemData;
            private TextView txTitle;
            private ImageView imgCover;

            @Override
            public void onClick(View v) {
                Intent intent = new Intent(v.getContext(), PhotoWallActivity.class);
                intent.addFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);
                intent.putExtra(PhotoWallActivity.EXTRA_FOLDER_PATH, itemData.pathName);
                ((Activity) v.getContext()).startActivityForResult(intent, RESULT_CODE_WALL);
            }
        }

        @Override
        public int getItemCount() {
            return photoAlbumList.size();
        }

        @Override
        public ViewHolder onCreateViewHolder(ViewGroup viewGroup, int i) {
            View view = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.recycler_photo_album, viewGroup, false);
            ViewHolder viewHolder = new ViewHolder(view);
            viewHolder.txTitle = (TextView) view.findViewById(R.id.tx_title);
            viewHolder.imgCover = (ImageView) view.findViewById(R.id.img_cover);
            return viewHolder;
        }

        @Override
        public void onBindViewHolder(final ViewHolder viewHolder, final int i) {
            final PhotoAlbum photoAlbum = photoAlbumList.get(i);
            String albumName = "";
            if (!TextUtils.isEmpty(photoAlbum.pathName)) {
                int idx = photoAlbum.pathName.lastIndexOf("/");
                if (idx >= 0) albumName = photoAlbum.pathName.substring(idx + 1);
                else albumName = photoAlbum.pathName;
            }
            viewHolder.txTitle.setText(albumName + "(" + photoAlbum.fileCount + ")");
            Glide.with(viewHolder.itemView.getContext()).load(photoAlbum.firstImagePath).into(viewHolder.imgCover);
            viewHolder.itemData = photoAlbum;
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        switch (requestCode) {
            case RESULT_CODE_WALL:
                if (resultCode == RESULT_OK) {
                    setResult(RESULT_OK, data);
                    finish();
                }
                break;
        }
    }
}
